package cn.edu.ahu.aircondition.modbus.service.dao;


import cn.edu.ahu.aircondition.modbus.service.entity.AirConStatusEntity;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import javax.transaction.Transactional;
import java.util.List;

/**
 *
 * Created by ahu on 2017/6/6.
 */
public class AirConStatusDao{
    private SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();

    /**
     * 根据deviceAddress获取状态信息
     * @param deviceAddressList 设备地址队列
     * @return 设备状态信息
     */
    public List<AirConStatusEntity> listAirConStatusCurByDeviceAddress(List<Integer> deviceAddressList){
        Transaction transaction = sessionFactory.getCurrentSession().getTransaction();
        transaction.begin();
        Session session = sessionFactory.getCurrentSession();
        //开始事务
        String queryString = "FROM AirConStatusEntity AS airConStatusEntity " +
                "WHERE airConStatusEntity.deviceAddress IN :deviceAddressList";
        List<AirConStatusEntity> list =  session.createQuery(queryString,AirConStatusEntity.class).
                setParameter("deviceAddressList",deviceAddressList).getResultList();
        transaction.commit();
        session.close();
        return list;
    }

    /**
     * 更新数据库中空调状态信息
     * @param airConStatusCurEntityList    空调状态信息List
     */
    public void updateAirConStatusCur(List<AirConStatusEntity> airConStatusCurEntityList){
        Transaction transaction = sessionFactory.getCurrentSession().getTransaction();
        transaction.begin();
        Session session = sessionFactory.getCurrentSession();
        for (AirConStatusEntity airConStatusCurEntity : airConStatusCurEntityList){
            session.update(airConStatusCurEntity);
        }
        transaction.commit();
        session.close();
    }
}